package com.tarena.practice.manage.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tarena.practice.manage.mapper.TopicMapper;
import com.tarena.practice.manage.pojo.Topic;
import com.tarena.practice.manage.service.UploadFileService;
import com.tarena.practice.manage.util.Excel2JsonUtil;
import com.tarena.practice.manage.util.UploadFileUtils;
import com.tarena.practice.manage.vo.PicUploadResult;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("uploadFile/")
public class UploadFileController {
	private final static ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private TopicMapper topicMapper;

	@Autowired
	private UploadFileService uploadFileService;
	
	@Autowired
	private UploadFileUtils uploadUtils;
	
	@RequestMapping(value="excel", method=RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam(value="fileData", required=false) MultipartFile file ,
            HttpServletRequest request, HttpServletResponse response)throws Exception {
		// 文件转换成输入流
		String oldFileName = file.getOriginalFilename();
		String extFileName = oldFileName.substring(oldFileName.lastIndexOf("."));
        FileInputStream fis=(FileInputStream) file.getInputStream();
        String dir = "/excel/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";
        String path = uploadUtils.getBasePath() + dir;
        File _dir = new File(path);
		if (!_dir.exists()) {
			_dir.mkdirs();
		}
		String newFileName = System.currentTimeMillis() + "" + RandomUtils.nextInt(100, 999) + extFileName;
		file.transferTo(new File(path + newFileName));
		List<JSONObject> jsonList = Excel2JsonUtil.excContrel2Jsonoller(path + newFileName);
		for (JSONObject jsonObject : jsonList) {
			//System.out.println(jsonObject);
			String jsonData = jsonObject.toString();
			Topic topic = mapper.readValue(jsonData, Topic.class);
			topic.setCreateTime(new Date());
			topic.setUpdateTime(topic.getCreateTime());
			System.out.println(topic.toString());
			System.out.println("aaaa" + topic);
			topicMapper.insertSelective(topic);
		}
		return "上传成功";
	}
	
	
	
	@RequestMapping(value="img", method=RequestMethod.POST)
	@ResponseBody
	public PicUploadResult uploadImg(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response){
		// 构造哟个返回的空对象
				PicUploadResult result = new PicUploadResult();
				// 判断后缀,获取原名称
				String oldFileName = multipartFile.getOriginalFilename();
				// 截取后缀
				String extFileName = oldFileName.substring(oldFileName.lastIndexOf("."));
				// 正则判断合法性
				if (!extFileName.matches("^.(jpg|png|gif)$")) {
					result.setError(1);
					return result;
				}

				try {
					// 判断木马 BufferedImage判断是否有宽高
					BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
					// getHeight()未抛出异常，证明数据流中包含有宽高的属性，不是木马
					result.setHeight(bufferedImage.getHeight() + "");
					result.setWidth(bufferedImage.getWidth() + "");
					// 以上内容未判断是否是木马
					// 生成路径 images\2018\07\26
					String dir = uploadUtils.getImgPath() + new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";
					// 拼接磁盘路径
					String path = uploadUtils.getBasePath() + dir;
					System.out.println(path);
					String urlPath = "http://"+uploadUtils.getAccessFile() + dir;
					// 创建磁盘目录，等待输出文件
					File _dir = new File(path);
					if (!_dir.exists()) {
						_dir.mkdirs();
					}
					
					// 计算文件重命名
					String newFileName = System.currentTimeMillis() + "" + RandomUtils.nextInt(100, 999) + extFileName;
					System.out.println(newFileName);
					result.setUrl(urlPath + newFileName);
					
					// 写出磁盘
					multipartFile.transferTo(new File(path + newFileName));
					result.setError(0);
				} catch (Exception e) {
					e.printStackTrace();
					result.setError(1);
				}
				return result;
		
	} 
}
